package com.ljb.nfc_demo.nfc;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.ljb.nfc_demo.R;

import static com.ljb.nfc_demo.R.id.bt_write;

/**
 * Created by ljb on 2017/7/13.
 */

public class WriteActivity extends BaseNFCActivity implements View.OnClickListener {
    private static final String TAG = "WriteActivity";
    private EditText et_data;

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, WriteActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write);
        initUI();
    }

    private void initUI() {
        et_data = (EditText) findViewById(R.id.et_data);
        findViewById(bt_write).setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e(TAG, "onNewIntent: 发现新的intent对象" + intent.getAction());
        if (isWrite) {
            Toast.makeText(this, "检测到NFC标签,可以进行读写操作", Toast.LENGTH_SHORT).show();

            boolean result = nfcUtils.write(write_data, intent);

            if (result) {
                Toast.makeText(this, "写入数据成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "写入数据失败", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private boolean isWrite = false;
    private String write_data = "";

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bt_write) {//写
            String data = et_data.getText().toString().trim();
            if (TextUtils.isEmpty(data)) {
                Toast.makeText(this, "写入内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            write_data = data;
            isWrite = true;
            Toast.makeText(this, "请靠近NFC标签,进行写入操作", Toast.LENGTH_SHORT).show();
        }
    }
}
